﻿(function () {
    "use strict";
    var nav = WinJS.Navigation;
    var fun = {
        noData : false,
        getVideoDataList: function (url) {
            var _this = this;
            var dataList = new WinJS.Binding.List();
            //请求数据并将xml转换成josn数组
            WinJS.xhr({
                url: url,
                headers: {
                    "If-Modified-Since": "Mon, 27 Mar 1972 00:00:00 GMT"
                }
            }).then(function (data) {
                if (!data.responseXML.querySelectorAll("article")[0]) {
                    _this.noData = true;
                }
                var items = data.responseXML.querySelectorAll("article");
                for (var i = 0; i < items.length; i++) {
                    var temp = {};
                    temp.className = 'listTemplate'
                    temp.title = items[i].attributes['t'].value;
                    temp.picture = items[i].attributes['p'].value;
                    temp.date = items[i].attributes['date'].value;
                    temp.classes = items[i].attributes['classes'].value;
                    temp.actor = items[i].attributes['actor'].value;
                    dataList.push({
                        className: temp.className,
                        title: temp.title,
                        picture: temp.picture,
                        date: temp.date,
                        classes: temp.classes,
                        actor: temp.actor
                    });
                }
            }, function (data) {
                return "disconnect";
            });
                return dataList
        },

        getNewsDataList: function (url) {
            var _this = this;
            var dataList = new WinJS.Binding.List();
            //请求数据并将xml转换成josn数组
            WinJS.xhr({
                url: url,
                headers: {
                    "If-Modified-Since": "Mon, 27 Mar 1972 00:00:00 GMT"
                }
            }).then(function (data) {
                if (!data.responseXML.querySelectorAll("article")[0]) {
                    _this.noData = true;
                }
                var items = data.responseXML.querySelectorAll("article");
                for (var i = 0; i < items.length; i++) {
                    var temp = {};
                    if (i == 0 || i%4 == 0) {
                        temp.className = 'largeListTemplate'
                    }
                    else {
                        temp.className = 'listTemplate'
                    }
                    temp.title = items[i].attributes['t'].value;
                    temp.picture = items[i].attributes['p'].value;
                    temp.date = items[i].attributes['date'].value;
                    temp.classes = items[i].attributes['classes'].value;
                    temp.id = items[i].attributes['id'].value;
                    temp.actor = items[i].attributes['n'].value;
                    dataList.push({
                        className: temp.className,
                        title: temp.title,
                        picture: temp.picture,
                        date: temp.date,
                        classes: temp.classes,
                        id:temp.id,
                        actor: temp.actor
                    });
                }
            }, function (data) {
                return "disconnect";
            });
                return dataList
        },

        getPictureDataList: function (url) {
            var _this = this;
            var dataList = new WinJS.Binding.List();
            //请求数据并将xml转换成josn数组
            WinJS.xhr({
                url: url,
                headers: {
                    "If-Modified-Since": "Mon, 27 Mar 1972 00:00:00 GMT"
                }
            }).then(function (data) {
                if (!data.responseXML.querySelectorAll("article")[0]) {
                    _this.noData = true;
                }
                var items = data.responseXML.querySelectorAll("article");
                for (var i = 0; i < items.length; i++) {
                    var temp = {};
                    temp.className = 'largeListTemplate';
                    temp.title = items[i].attributes['t'].value;
                    temp.picture = items[i].attributes['url'].value;
                    temp.date = items[i].attributes['date'].value;
                    temp.classes = items[i].attributes['classes'].value;
                    temp.id = items[i].attributes['id'].value;
                    temp.actor = items[i].attributes['n'].value;
                    dataList.push({
                        className: temp.className,
                        title: temp.title,
                        picture: temp.picture,
                        date: temp.date,
                        classes: temp.classes,
                        id: temp.id,
                        actor: temp.actor
                    });
                }
            }, function (data) {
                return "disconnect";
            });
            return dataList
        },

        getPictureDetailDataList: function (url) {
            var _this = this;
            var dataList = new WinJS.Binding.List();
            //请求数据并将xml转换成josn数组
            WinJS.xhr({
                url: url,
                headers: {
                    "If-Modified-Since": "Mon, 27 Mar 1972 00:00:00 GMT"
                }
            }).then(function (data) {
                var items = data.responseXML.querySelectorAll("article");
                for (var i = 0; i < items.length; i++) {
                    var temp = {};
                    temp.picture = items[i].attributes['p'].value;
                    dataList.push({
                        picture: temp.picture
                    });
                }
            }, function (data) {
                //document.getElementById('test').innerHTML = "网络连接错误";
                return "disconnect";
            });
            return dataList
            //_this.bindDate(element, dataList, listviewID, listTemplate);
        },

        getNewsDetailDataList: function (url) {
            var _this = this;
            var dataList = null;
            //请求数据并将xml转换成josn数组
            WinJS.xhr({
                url: url,
                responseType: "text",
                headers: {
                    "If-Modified-Since": "Mon, 27 Mar 1972 00:00:00 GMT"
                }
            }).then(function (data) {
                var items = data.responseText;
                items = items.replace(/(\<\!\[CDATA\[\<root\>)|(\<\/root\>]]\>)/g, '');
                items = items.replace(/(\<\!\[CDATA\[)|(]]\>)/g, '');
                items = items.replace(/\n/g, '&lt;br/&gt;');
                items = new DOMParser().parseFromString(items, "text/xml");
                
                items = $(items).find("p");
                var content = '';
                items.each(function () {
                    if ($(this).attr('classe') == 't') {
                        content += ('<p>' + $(this).text() + '</p>');
                    }
                    else {
                        content += ('<img src="' + $(this).attr('src') + '"/>');
                    }
                })
                dataList = content;
                MSApp.execUnsafeLocalFunction(
                    function () { $('.newsDetail-content').html((dataList)); }
                );
            }, function (data) {
                //document.getElementById('test').innerHTML = "网络连接错误";
                return "disconnect";
            });
            return dataList
        },

        getCategory: function (options) {
            var options = options;
            switch (options.dataType) {
                case 'video':
                    var getDataList = page.fun.getVideoDataList;
                    var allUrl = 'http://app.hbook.us/flashinterface/GetMovieByPage.ashx?page=1&pagesize=1000&topicid=5';
                    break;
                case 'news':
                    var getDataList = page.fun.getNewsDataList;
                    var allUrl = 'http://app.hbook.us/flashinterface/GetNewsByPage.ashx?page=1&pagesize=1000&topicid=5';
                    break;
                case 'picture':
                    var getDataList = page.fun.getPictureDataList;
                    var allUrl = 'http://app.hbook.us/flashinterface/GetPicturesByPage.ashx?page=1&pagesize=1000&topicid=5';
                    break;
            }
            var _this = this;
            var dataList = [];
            var select = $('.category-select');
            WinJS.xhr({
                url: options.url,
                headers: {
                    "If-Modified-Since": "Mon, 27 Mar 1972 00:00:00 GMT"
                }
            }).then(function (data) {
                var items = data.responseXML.querySelectorAll("category");
                for (var i = 0; i < items.length; i++) {
                    var temp = {};
                    temp.title = items[i].attributes['title'].value;
                    dataList.push({
                        title: temp.title
                    });
                };
                dataList.unshift({
                    title: '全部'
                })

            }, function (data) {
                return "disconnect";
            }).then(function () {
                var temp = '';
                $.each(dataList, function (i) {
                    var value = dataList[i].title;
                    if (i == 0) {
                        temp += '<option value="' + allUrl + '">' + value + '</option>';
                    }
                    else {
                        temp += '<option value="' + value + '">' + value + '</option>';
                    }
                });
               select.html(window.toStaticHTML(temp));
            }).then(function () {
                var o = $('.category-select');
                o.change(function () {
                    if ($(this).val().indexOf('http') > -1) {
                        var data = getDataList($(this).val());
                    }
                    else {
                        var o = encodeURIComponent($(this).val());
                        var data = getDataList(options.dataList + o);
                    }
                    page.fun.bindDate(
                        {
                            dataType: options.dataType,
                            element: options.element,
                            dataList: data,
                            listviewID: "#listPage-listView",
                            listTemplate: "#listPageTemplateWrap",
                            LayoutType: "GridLayout",
                            loadMorePages: true
                        }
                    );
                });
            });
        },

        getSearchResults: function(options){
            var queryText = options.queryText;
            var videoData = page.fun.getVideoDataList('http://app.hbook.us/flashinterface/GetMovieByPage.ashx?page=1&pagesize=1000&topicid=5&title=' + queryText);
            var newsData = page.fun.getNewsDataList('http://app.hbook.us/flashinterface/GetNewsByPage.ashx?page=1&pagesize=1000&topicid=5&title=' + queryText);
            var pictureData = page.fun.getPictureDataList('http://app.hbook.us/flashinterface/GetPicturesByPage.ashx?page=1&pagesize=1000&topicid=5&title=' + queryText);

            $('#search-category a').click(function () {
                switch ($(this).attr('id')) {
                    case 'videoResults-btn':
                        var Data = page.fun.getVideoDataList('http://app.hbook.us/flashinterface/GetMovieByPage.ashx?page=1&pagesize=1000&topicid=5&title=' + queryText);
                        page.fun.bindDate(
                            {
                                dataType: "video",
                                element: options.element,
                                dataList: Data,
                                listviewID: "#listPage-listView",
                                listTemplate: "#listPageTemplateWrap",
                                LayoutType: "GridLayout",
                                loadMorePages: true
                            }
                        );
                        var getDataList = page.fun.getVideoDataList;
                        break;
                    case 'pictureResults-btn':
                        var getDataList = page.fun.getNewsDataList;
                        var allUrl = 'http://app.hbook.us/flashinterface/GetNewsByPage.ashx?page=1&pagesize=1000&topicid=5';
                        break;
                    case 'newsResults-btn':
                        var getDataList = page.fun.getPictureDataList;
                        var allUrl = 'http://app.hbook.us/flashinterface/GetPicturesByPage.ashx?page=1&pagesize=1000&topicid=5';
                        break;
                }
            });

        },

        groupInfo: function(){
            return {
                enableCellSpanning: true,
                cellWidth: 138,
                cellHeight: 210
            };
        },

        bindDate: function (options) {
            $('.loading').show();
            var _this = this;
            var options = options;
            switch (options.dataType)
            {
                case 'video':
                    var detailPageUrl = "/pages/videoDetail/videoDetail.html";
                    break;
                case 'news':
                    var detailPageUrl = "/pages/newsDetail/newsDetail.html";
                    break;
                case 'picture':
                    var detailPageUrl = "/pages/pictureDetail/pictureDetail.html";
                    break;
            }
            var o = setInterval(function () {
                if (options.dataList.length > 1) {
                    clearInterval(o);
                    var listView = options.element.querySelector(options.listviewID).winControl;
                    listView.itemTemplate = options.element.querySelector(options.listTemplate);
                    listView.itemDataSource = options.dataList.dataSource;
                    
                    if (options.LayoutType == 'ListLayout') {
                        listView.layout = new WinJS.UI.ListLayout();
                        listView.tapBehavior = 'directSelect';
                        listView.loadingBehavior = 'incremental';
                        listView.pagesToLoad = 2;
                        listView.automaticallyLoadPages = true;
                        listView.pagesToLoadThreshold = 1;
                        listView.forceLayout();
                        $('.loading').hide();

                    }
                    if (options.LayoutType == 'GridLayout') {
                        listView.selectionMode = 'none';
                        listView.layout = new WinJS.UI.GridLayout({ groupInfo: _this.groupInfo }); 
                    }
                    if (options.LayoutType == 'GridLayout' && options.loadMorePages == true) {
                        listView.tapBehavior = 'directSelect';
                        listView.loadingBehavior = 'incremental';
                        listView.pagesToLoad = 1;
                        listView.automaticallyLoadPages = false;
                        $('.loading').hide();

                        var v = null;
                        $('.win-viewport').scroll(function () {
                            if (listView.loadingState == "complete") {
                                if (!v) {
                                    v = $('.win-surface').innerWidth() - $('body').width() + parseInt($('.win-surface').css('marginLeft'));
                                }
                            }
                             $('#test').html(v);
                             if ($(this).scrollLeft() == v) {
                                 $('.loading').show();
                                 setTimeout(function () {
                                     listView.loadMorePages();
                                     v = null;
                                     $('.loading').hide();
                                 }, 500)
   
                            }
                        })
                        listView.forceLayout();
                    }

                    listView.oniteminvoked = itemInvoked.bind(this);
                    page.frontItemCount++;
                }
            }, 10);

            function itemInvoked(args) {
                var item = options.dataList.getAt(args.detail.itemIndex)
                if (options.LayoutType == 'ListLayout' && options.dataType == 'video') {
                    _this.playVideo(item);
                }
                else if (options.LayoutType == 'ListLayout' && options.dataType == 'picture') {
                    var data = _this.getPictureDetailDataList('http://app.hbook.us/flashinterface/GetPicturesDetails.ashx?picID=' + item.id);
                    var o = options.element.querySelector('#pictureFlipView').winControl;
                    _this.bindFlipViewDate(
                       {
                        element: options.element,
                        dataList: data,
                        listviewID: "#pictureFlipView",
                        listTemplate: "#FlipViewTemplate",
                        LayoutType: "ListLayout"
                       }
                    );
                    //o.itemDataSource = data.dataSource;
                    options.element.querySelector(".picture-t").textContent = item.title;
                }
                else {
                    nav.navigate(detailPageUrl, item);
                }
            }
        },

        bindFlipViewDate: function (options) {
            var _this = this;
            var o = setInterval(function () {
                if (options.dataList.length > 1) {
                    clearInterval(o);
                    var listView = options.element.querySelector(options.listviewID).winControl;
                    listView.itemTemplate = options.element.querySelector(options.listTemplate);
                    listView.itemDataSource = options.dataList.dataSource;
                    listView.forceLayout();
                    //element.querySelector(".picture-t").textContent = item.title;
                }
            }, 10);
        },

        playVideo: function (item) {
            var videoUrl = item.actor;
            var videoTitle = item.title;
            var mp4Url = "http://3g.youku.com/pvs?id=" + videoUrl.match(/(http:\/\/v\.youku.com\/v_show\/id_)(.*)(\.html)/)[2] + "&format=3gphd";
            var videoPlayBox = document.getElementById('video-box');
            videoPlayBox.src = mp4Url;
            $(".video-t").html(videoTitle)
        },

        linkClickEventHandler: function (eventInfo) {
            eventInfo.preventDefault();
            var link = eventInfo.target;
            WinJS.Navigation.navigate(link.href);
        },

        confirmNetwork: function (o, element, callback) {
            var that = this;
            var msg = new Windows.UI.Popups.MessageDialog("亲，您需要一个网络，请检查您的网络连接");
            msg.title = '提示'
            msg.commands.append(new Windows.UI.Popups.UICommand("重试", commandInvokedHandler));
            if (networkInfo() == null) {
                msg.showAsync();
            }
            else {
                callback(element);
            };
            function commandInvokedHandler() {
                setTimeout(function () {
                    that.confirmNetwork(o, element, callback);
                },3000)   
            }
            function networkInfo(){
                return Windows.Networking.Connectivity.NetworkInformation.getInternetConnectionProfile()
            }
        }

    }
 


    //设置全局变量
    var publicMembers =
        {
            fun: fun,
            frontItemCount: 0,
            temp:0
        };
    WinJS.Namespace.define("page", publicMembers);
})();